const stompClient = new StompJs.Client({
    brokerURL: 'ws://192.168.169.83:9094/ws',
    // 测试集群使用，需要配合Nginx
    // brokerURL: 'ws://cluster.local:2980/ws',
    // 启用重新连接
    reconnectDelay: 1000,
    connectionTimeout: 3000,
    heartbeatIncoming: 3000,
    heartbeatOutgoing: 3000
    // 自定义连接头
    // connectHeaders: {
    //     'username': 'looveh',
    //     'age': 18
    // }
});


stompClient.onConnect = (frame) => {
    setConnected(true);
    console.log('Connected: ' + frame);
    stompClient.subscribe('/exchange/mcExchange/a.b.*.*', (greeting) => {
        console.log(greeting)
        showGreeting(JSON.parse(greeting.body).content);
        // 通过ack方法对消息做ACK
        //greeting.ack();
        //stompClient.ack(greeting.headers["message-id"], '/exchange/mcExchange/a.b.*.*', {})
        //stompClient.nack(greeting.headers["message-id"], '/exchange/mcExchange/a.b.*.*', {})
    }, {
        // 队列持久化
        'durable': true,
        'auto-delete': false,
        // 设置ack模式，支持[auto, client, client-individual]
        // auto: 自动ack
        // client: 客户端ack,批量操作
        // client-individual: 单消息确认
        'ack': 'client-individual'
    });
};
stompClient.debug = function(str) {
    // append the debug log to a #debug div somewhere in the page using JQuery:
    // 获取当前时间
    const currentTime = new Date();
    // 将时间转化为可读的字符串格式
    const currentTimeStr = currentTime.toISOString();

    // 将调试信息附加到 #debug div 中
    $("#debug").append("[" + currentTimeStr + "] ##### " + str + "\n");
};
stompClient.onWebSocketError = (error) => {
    // 获取当前时间
    const currentTime = new Date();

    // 提取小时、分钟、秒和毫秒
    const hours = currentTime.getHours();
    const minutes = currentTime.getMinutes();
    const seconds = currentTime.getSeconds();
    const milliseconds = currentTime.getMilliseconds();

    // 格式化时间字符串
    const timeStr = `${hours}:${minutes}:${seconds}.${milliseconds}`;

    // 将时间附加到错误消息之后
    const errorMessage = '[' + timeStr + '] Error with websocket ' + error;

    console.error(errorMessage);
};


stompClient.onStompError = (frame) => {
    console.error('Broker reported error: ' + frame.headers['message']);
    console.error('Additional details: ' + frame.body);
};

function setConnected(connected) {
    $("#connect").prop("disabled", connected);
    $("#disconnect").prop("disabled", !connected);
    if (connected) {
        $("#conversation").show();
    }
    else {
        $("#conversation").hide();
    }
    $("#greetings").html("");
}

function connect() {
    stompClient.activate();
}

function disconnect() {
    stompClient.deactivate();
    setConnected(false);
    console.log("Disconnected");
}

function sendName() {
    stompClient.publish({
        destination: "/app/hello1",
        body: JSON.stringify({'name': $("#name").val()})
    });
}

function showGreeting(message) {
    $("#greetings").append("<tr><td>" + message + "</td></tr>");
}

$(function () {
    $("form").on('submit', (e) => e.preventDefault());
    $( "#connect" ).click(() => connect());
    $( "#disconnect" ).click(() => disconnect());
    $( "#send" ).click(() => sendName());
});
